﻿/*

Copyright (c) 2009, Stephen Remde
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the <organization> nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY STEPHEN REMDE ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL STEPHEN REMDE BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Threading;
using System.Windows.Data;

namespace ConceptLink
{
    /// <summary>
    /// this UserControl helps the user search for a selected concept.
    /// </summary>
    public partial class ConceptSelector : UserControl
    {
        public ConceptSelector()
        {
            InitializeComponent();
        }
        
        string queued_concept = "";

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            // user typed something (we might already be servicing an async request)
        
            string old_queued_concept = queued_concept;            
            
            queued_concept = (sender as TextBox).Text;

            if (old_queued_concept == "" && queued_concept != "")
            {
                // there isnt already a request in progress
                // so start one!

                ShowLoading();

                Search.Get(queued_concept, ProcessResults);
            }
        }
        
        private void ProcessResults(string article, ConceptLink.Search.SearchResult[] results)
        {            
            // async search request returned
            if (article == queued_concept)
            {                
                // its the results for the most current search so update display.

                queued_concept = "";
                
                Results.SelectedIndex = -1;
                Results.ItemsSource = results;
                
                HideLoading();                
            }
            else
            {                
                // we have had another request since then...
                Search.Get(queued_concept, ProcessResults);
            }
        }

        private void HideLoading()
        {
            Loading.Visibility = Visibility.Collapsed;

            if (Results.Items.Count == 0)
                NoResults.Visibility = Visibility.Visible;
            else
            {
                Results.Visibility = Visibility.Visible;
                Results.SelectedIndex = 0;
            }
        }

        private void ShowLoading()
        {
            Loading.Visibility = Visibility.Visible;
            Results.Visibility = Visibility.Collapsed;
            NoResults.Visibility = Visibility.Collapsed;          
        }

        /// <summary>
        /// Gets the currently selected concept or null is none selected
        /// </summary>
        public Search.SearchResult Selected { get { return Results.SelectedItem as Search.SearchResult; } }
        
        /// <summary>
        /// Gets/Sets the prompt to display.
        /// </summary>
        public string Prompt { get { return PromptLabel.Text; } set { PromptLabel.Text = value; } }
        
        /// <summary>
        /// Called when the selected concept is changed.
        /// </summary>
        public event ConceptChangedEventHandler ConceptChanged;

        public delegate void ConceptChangedEventHandler(ConceptSelector sender, Search.SearchResult item);

        private void Results_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ConceptChanged != null)
                ConceptChanged(this, Results.SelectedItem as Search.SearchResult);
        }

        // clears the current concept.
        public void Clear()
        {
            Concept.Text = ""; 
            
            Loading.Visibility = Visibility.Collapsed;
            Results.Visibility = Visibility.Collapsed;
            NoResults.Visibility = Visibility.Collapsed;           
        }
    }

    /// <summary>
    /// helper class to display %ages in silverlight
    /// </summary>
    public class PercentageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            float f = (float)value;
            if (f < 0f)
                return f.ToString("??%");
            else if (f < .1f)
                return f.ToString("0.0%");
            else
                return f.ToString("0%");
        }
        #region IValueConverter Members        
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}